package com.monitorRoutine.monitorRoutineController.service.impl;

import com.alibaba.fastjson.JSON;
import com.monitorRoutine.monitorRoutineController.Initialize;
import com.monitorRoutine.monitorRoutineController.entity.ControlCommand;
import com.monitorRoutine.monitorRoutineController.entity.ControlCommandFile;
import com.monitorRoutine.monitorRoutineController.service.ControlCommandService;
import com.monitorRoutine.monitorRoutineController.service.ExecuteCommandService;
import com.monitorRoutine.monitorRoutineController.util.DownloadUtil;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.jgit.api.Git;
import org.eclipse.jgit.api.MergeCommand;
import org.eclipse.jgit.api.errors.GitAPIException;
import org.eclipse.jgit.lib.ObjectId;
import org.eclipse.jgit.lib.RepositoryBuilder;
import org.eclipse.jgit.revwalk.RevTree;
import org.eclipse.jgit.revwalk.RevWalk;
import org.eclipse.jgit.transport.CredentialsProvider;
import org.eclipse.jgit.transport.UsernamePasswordCredentialsProvider;
import org.eclipse.jgit.treewalk.CanonicalTreeParser;
import org.eclipse.jgit.treewalk.FileTreeIterator;
import org.eclipse.jgit.util.FS;
import org.eclipse.jgit.util.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.eclipse.jgit.lib.Repository;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Slf4j
@Service
public class ExecuteCommandServiceImpl implements ExecuteCommandService {
    HashMap<String,Process> processHashMap=new HashMap<>();
    private final ExecutorService downloadExecutor = Executors.newSingleThreadExecutor();
    @Autowired
    ControlCommandService controlCommandService;
    @Override
    public void rebootComputer() {
        String os = System.getProperty("os.name").toLowerCase();
        String command;

        if (os.contains("win")) {
            // Windows 系统
            command = "shutdown /r /f /t 0";
        } else if (os.contains("nix") || os.contains("nux") || os.contains("mac")) {
            // Linux 或 macOS 系统
            command = "sudo reboot";
        } else {
            System.out.println("不支持的操作系统");
            return;
        }
        try {
            Process process = Runtime.getRuntime().exec(command);
            process.waitFor(); // 等待命令执行完成
            System.out.println("系统正在重启...");
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
    }

    @Override
    public Process  startPython(String filePath) throws IOException {
            String os = System.getProperty("os.name").toLowerCase();
            String pythonCmd=null;
            if (os.contains("win")) {
                // Windows 系统
                pythonCmd = "python";
            } else if (os.contains("nix") || os.contains("nux") || os.contains("mac")) {
                // Linux 或 macOS 系统
                pythonCmd = "python3";
            } else {
                System.out.println("不支持的操作系统");
                return null;
            }


        String[] cmd = {pythonCmd, filePath};
        return Runtime.getRuntime().exec(cmd);


    }
    @Override
    public boolean  startBat(String filePath) throws IOException,InterruptedException{

        /**
         * 打开cmd页面
         */
        Process process = Runtime.getRuntime().exec("cmd /c start cmd.exe /K \""+filePath+"\"");

//        Process process = Runtime.getRuntime().exec(filePath);
//        int exitCode = process.waitFor();
        return true;
    }

    @Override
    public boolean closurePython(Process process)  {
        process.destroy();
        return true;
    }

    @Override
    public boolean transferringFiles(ControlCommand controlCommand) throws IOException {
//        http://localhost:6678/monitorRoutineServer/file/download/{fileName}
        String SERVER_ADDRESS= Initialize.configurationMapper.get("monitorRoutineController.format.serverAddress");

        ControlCommandFile controlCommandFile = JSON.parseObject(controlCommand.getCommandDetails(), ControlCommandFile.class);
        String downloadPath=SERVER_ADDRESS+"/file/download/"+controlCommandFile.getFilename();
        downloadExecutor.submit(() -> {
            try {
                 DownloadUtil.downloadFileWithRetry(downloadPath, controlCommandFile.getFilrPath());
                controlCommand.setCompletiontime(new Date());
                controlCommand.setExecute("3");
                controlCommandService.update(controlCommand);
            } catch (Exception e) {
                controlCommand.setCompletiontime(new Date());
                controlCommand.setExecute("4");
                controlCommandService. update(controlCommand);
                e.printStackTrace();
            }

        });
        return true;
    }

    @Override
    public boolean processExists(String name) {
        try {
            // 构建命令以检查进程
//            ProcessBuilder builder = new ProcessBuilder("cmd", "/c", "tasklist /FI \"IMAGENAME eq " + name + "\" | find /I \"" + name + "\"");

            ProcessBuilder builder = new ProcessBuilder("cmd", "/c", "tasklist /FI \"IMAGENAME eq "+name+"\" | find /I \""+name+"\"");
            builder.redirectErrorStream(true);

            // 执行命令
            Process process = builder.start();

            // 读取命令执行后的输出
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line;
            boolean exists = false;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
                exists = true;
                break;
            }

            // 等待命令执行完成
            process.waitFor();

            return exists;
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public boolean gitPull(ControlCommand controlCommand) throws Exception{
        Map<String, String> map = JSON.parseObject(controlCommand.getCommandDetails(), Map.class);
        String path = map.get("path");
        String username = map.get("username");
        String password = map.get("password");
        String remote = map.get("remote");
        Git git = Git.open(new File(path));
        CredentialsProvider credentialsProvider = new UsernamePasswordCredentialsProvider(username, password);

//        git.checkout().setAllPaths(true).call();
        git.pull()
                .setCredentialsProvider(credentialsProvider)
                .setFastForward(MergeCommand.FastForwardMode.NO_FF) // 确保不进行快进合并
                .call();
            git.close();

        return true;
    }
}
